package com.earthea.application.web.controller.monitor;

import com.earthea.application.common.annotation.Log;
import com.earthea.application.common.core.controller.BaseController;
import com.earthea.application.common.entity.BaseResult;
import com.earthea.application.common.entity.TableDataInfo;
import com.earthea.application.common.enums.BusinessType;
import com.earthea.application.common.utils.poi.ExcelUtil;
import com.earthea.application.framework.web.service.SysPasswordService;
import com.earthea.application.system.domain.entity.SysLoginLog;
import com.earthea.application.system.domain.service.ISysLoginLogService;
import com.earthea.application.system.entity.request.SysLoginLogReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 系统访问记录
 */
@RestController
@RequestMapping("/rest/monitor/loginlog")
public class SysLoginLogController extends BaseController {
    @Autowired
    private ISysLoginLogService loginLogService;

    @Autowired
    private SysPasswordService passwordService;

    @PreAuthorize("@ss.hasPermi('monitor:loginlog:list')")
    @GetMapping("/list")
    public TableDataInfo<SysLoginLog> list(SysLoginLogReq req) {
        return loginLogService.select(req);
    }

    @Log(title = "登录日志", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('monitor:loginlog:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysLoginLogReq req) {
        TableDataInfo<SysLoginLog> info = loginLogService.select(req);
        ExcelUtil.export(response, "登录日志", info.getRows(), SysLoginLog.class);
    }

    @PreAuthorize("@ss.hasPermi('monitor:loginlog:remove')")
    @Log(title = "登录日志", businessType = BusinessType.DELETE)
    @DeleteMapping("/{infoIds}")
    public BaseResult remove(@PathVariable List<Long> infoIds) {
        return toResult(loginLogService.batchDelete(infoIds));
    }

    @PreAuthorize("@ss.hasPermi('monitor:loginlog:remove')")
    @Log(title = "登录日志", businessType = BusinessType.CLEAN)
    @DeleteMapping("/clean")
    public BaseResult clean() {
        loginLogService.clean();
        return success();
    }

    @PreAuthorize("@ss.hasPermi('monitor:loginlog:unlock')")
    @Log(title = "账户解锁", businessType = BusinessType.OTHER)
    @GetMapping("/unlock/{userName}")
    public BaseResult unlock(@PathVariable("userName") String userName) {
        passwordService.clearLoginRecordCache(userName);
        return success();
    }
}
